<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { listMainIn, queryChartForHour, querySpcAnalysis, specCurrent } from "@/api/leadScreenNew";
import dayjs from "dayjs";
import { onMounted, ref } from "vue";
import Carousel from "./Carousel.vue";
import CarouselItem from "./CarouselItem.vue";
import LineChartVue from "./LineChart.vue";
import LineDialog from "./LineDialog.vue";
import Pie from "./Pie.vue";
import Title from "./Title.vue";
import Empty from "./empty.vue";
import { getMarkLineData, usePolling } from "./hooks";
const dkData = ref();
// 初始化机械科数据
const wcsData: any = ref({});
const pcwData: any = ref({});
const pqylData: any = ref({});
const transformData = (data, dataSource, config = [], nameDesc?: Object) => {
  const xAxisData = dataSource.xaxis.map(item => item.split(" ")[1]);
  const panelList = dataSource.panelList
    .filter(item => config.includes(item.dictKey))
    .map(item => ({
      ...item,
      name: nameDesc ? nameDesc[item.dictKey] : item.title,
      data: item.details.map(item => item.value),
      xAxisData
    }));
  data.value = { ...dataSource, panelList };
};
const initJxkData = async () => {
  const data = await Promise.all([
    queryChartForHour({ dictKey: "WCSWSD", dictTypeCode: "MCTS" }),
    queryChartForHour({ dictKey: "PCWPVZB", dictTypeCode: "MCTS" }),
    queryChartForHour({ dictKey: "PQYLZB", dictTypeCode: "MCTS" })
  ]);

  transformData(wcsData, data[0], ["WCSWSD01", "WCSWSD03"], { WCSWSD01: "洁净室温度", WCSWSD03: "洁净室湿度" });
  transformData(pcwData, data[1], ["PCWPVZB001", "PCWPVZB002"], { PCWPVZB001: "PCW供水压力", PCWPVZB002: "PCW供水温度" });
  transformData(pqylData, data[2], ["PQYLZB02", "PQYLZB04", "PQYLZB01", "PQYLZB03"]);
};
// 初始化电科数据
const initDkData = async () => {
  const data = await listMainIn();

  const len = ceilDivide(data.length, 4);
  const arr = [];
  for (let index = 0; index < len; index++) {
    const child = data.slice(index * 4, (index + 1) * 4);
    arr.push(child);
  }
  dkData.value = arr;
};
// 初始化水科数据
const skData: any = ref({});
const initSkData = async () => {
  const data = await Promise.all([queryChartForHour({ dictKey: "UPW01" }), queryChartForHour({ dictKey: "WWT01" })]);
  const upwxAxisData = data[0]?.xaxis?.map(item => item.split(" ")[1]) || [];
  const upwData = {
    ...data[0],
    panelList:
      data[0].panelList?.map(item => ({
        ...item,
        name: item.title,
        data: item.details?.map(item => item.value) || [],
        xAxisData: upwxAxisData
      })) || []
  };
  const wwtxAxisData = data[1]?.xaxis?.map(item => item.split(" ")[1]) || [];
  const wwtData = {
    ...data[1],
    panelList:
      data[1].panelList?.map(item => ({
        ...item,
        name: item.title,
        data: item.details?.map(item => item.value) || [],
        xAxisData: wwtxAxisData
      })) || []
  };
  const len_0 = ceilDivide(data[0]?.panelList?.length);
  const len_1 = ceilDivide(data[1]?.panelList?.length);
  const len = len_0 > len_1 ? len_0 : len_1;
  const arr = [];
  for (let index = 0; index < len; index++) {
    const child = [upwData.panelList.slice(index * 2, (index + 1) * 2), wwtData.panelList.slice(index * 2, (index + 1) * 2)];
    arr.push(child);
  }
  skData.value.data = arr;
  skData.value.upwXaxis = upwData.xaxis;
  skData.value.wwtXaxis = wwtData.xaxis;
};
const ceilDivide = (a, b = 2) => {
  if (b === 0) throw new Error("Divisor cannot be zero");
  return Math.ceil(a / b);
};
// 初始化气化科数据

const qhkData = ref();
const qhkLoading = ref(true);
const initQhkData = async () => {
  qhkLoading.value = true;
  let now = new Date();
  let sevenDaysAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000); // 1天 = 24 * 60 * 60 * 1000 毫秒
  const startTime = dayjs(sevenDaysAgo).format("YYYY-MM-DD HH:mm:ss");
  let endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // 获取指标点位
  let pointList = [];
  const facCode = localStorage.getItem("facCode");
  if (facCode === "FAC_83abf9") {
    pointList = pointsData.value["LEADER_SCREEN_QHKYXZB"]?.children?.map(item => item.value);
  } else {
    pointList = pointsData.value[`LEADER_SCREEN_QHKYXZB_${facCode}`]?.children?.map(item => item.value);
  }
  if (!pointList) {
    qhkData.value = undefined;
    qhkLoading.value = false;
    return;
  }
  const res = await querySpcAnalysis({
    pointList,
    timePeriod: "minutes",
    startTime,
    endTime
  });
  const newRes = res.filter(item => item.pointValues);
  const data = newRes.map(item => {
    const obj = {
      name: item.indicatorName,
      max: item.uaclValue,
      min: item.laclValue,
      data: item.formatPointValues?.map(point => point.num) || [],
      unit: item.pointUnit || " ",
      xAxisData: item?.formatPointValues?.map(point => point.name) || [],
      markLineData: getMarkLineData(item)
    };
    return obj;
  });
  const len = ceilDivide(data.length, 4);
  const arr = [];
  for (let index = 0; index < len; index++) {
    const child = data.slice(index * 4, (index + 1) * 4);
    arr.push(child);
  }
  qhkData.value = arr;
  qhkLoading.value = false;
};
const pointsData = ref({});
const loading = ref(true);
const init = async () => {
  const data = await Promise.allSettled([initDkData(), initSkData(), initJxkData(), initQhkData()]);
  return null;
};
// 轮询
usePolling(init, {
  pollingInterval: 1 * 60 * 1000
});
onMounted(async () => {
  const obj = {};
  const data = await queryDictData({ typeCode: "LEADER_SCREEN_POINTS_NEW" });
  data?.forEach(item => (obj[item.value] = item));
  pointsData.value = obj;
  await init();
  loading.value = false;
});
const dialogLineData = ref();
const dialogVisible = ref(false);
const handleClick = data => {
  dialogLineData.value = data;
  dialogVisible.value = true;
};
const handleClickPie = async (mainKey, mainName) => {
  const res = await specCurrent(mainKey);
  const data = {
    name: mainName,
    data: res?.pointValues?.map(item => item.value) || [],
    unit: res?.pointUnit || " ",
    xAxisData: res?.formatPointValues?.map(item => item.name.split(" ")[1]) || []
  };
  dialogLineData.value = data;
  dialogVisible.value = true;
};
</script>
<template>
  <section class="mg-8">
    <px-row :gutter="8">
      <!-- 机械科运行 -->
      <px-col :span="6" class="screen-card-box">
        <div class="card-content">
          <div class="card-title">机械科运行指标</div>
          <div class="jxk-card-body">
            <Carousel v-if="skData.data && !loading">
              <CarouselItem>
                <px-row :gutter="8">
                  <px-col class="chart-box" :span="12" v-for="(chartData, i) in wcsData.panelList" :key="`wcsData${i}`">
                    <Title :title="chartData.name" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      class="pointer"
                      @click="handleClick(chartData)"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty v-else />
                  </px-col>
                  <px-col class="chart-box" :span="12" v-for="(chartData, i) in pcwData.panelList" :key="`pcwData${i}`">
                    <Title :title="chartData.name" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      class="pointer"
                      @click="handleClick(chartData)"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty v-else />
                  </px-col>
                </px-row>
              </CarouselItem>
              <CarouselItem>
                <px-row :gutter="8">
                  <px-col class="chart-box" :span="12" v-for="(chartData, i) in pqylData.panelList" :key="`pqylData${i}`">
                    <Title :title="chartData.name" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      class="pointer"
                      @click="handleClick(chartData)"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty v-else />
                  </px-col>
                </px-row>
              </CarouselItem>
            </Carousel>
          </div>
        </div>
      </px-col>
      <!-- 电科运行 -->
      <px-col :span="6" class="screen-card-box">
        <div class="card-content">
          <div class="card-title">电科运行指标</div>
          <div class="dk-card-body">
            <Carousel v-if="dkData && !loading">
              <CarouselItem v-for="(item, index) in dkData" :key="index">
                <px-row :gutter="8">
                  <px-col class="dk-card-item" :span="12" :key="item.mainName" v-for="dkItemData in item">
                    <Pie class="pointer" :data="dkItemData" @click="handleClickPie(dkItemData.mainKey, `${dkItemData.mainName} 用电情况`)"
                  /></px-col>
                </px-row>
              </CarouselItem>
            </Carousel>
          </div>
        </div>
      </px-col>
      <!-- 水科运行 -->
      <px-col :span="6" class="screen-card-box">
        <div class="card-content">
          <div class="card-title">水科运行指标</div>
          <div class="sk-card-body">
            <Carousel v-if="skData.data && !loading">
              <CarouselItem v-for="(item, index) in skData.data" :key="index">
                <px-row :gutter="8">
                  <px-col :span="24" class="row-title">UPW终端指标</px-col>
                  <px-col :span="12" v-for="(chartData, i) in item[0]" :key="`chartData${i}`">
                    <Title :title="chartData.title" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      @click="handleClick(chartData)"
                      class="sk-line-chart pointer"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty v-else />
                  </px-col>
                </px-row>
                <px-row :gutter="8">
                  <px-col :span="24" class="row-title">WWT总排指标</px-col>
                  <px-col :span="12" v-for="(chartData, i) in item[1]" :key="`chartData${i}`">
                    <Title :title="chartData.title" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      @click="handleClick(chartData)"
                      class="sk-line-chart pointer"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty class="sk-line-chart" v-else />
                  </px-col>
                </px-row>
              </CarouselItem>
            </Carousel>
          </div>
        </div>
      </px-col>
      <!-- 气化科运行 -->
      <px-col :span="6" class="screen-card-box">
        <div class="card-content">
          <div class="card-title">气化科运行指标</div>
          <div class="qhk-card-body">
            <Carousel v-if="qhkData && !loading">
              <CarouselItem v-for="(item, index) in qhkData" :key="index">
                <px-row :gutter="8">
                  <px-col class="chart-box" :span="12" v-for="(chartData, i) in item" :key="`chartData${i}`">
                    <Title :title="chartData.name" />
                    <LineChartVue
                      v-if="chartData.data?.length"
                      class="pointer"
                      @click="handleClick(chartData)"
                      :data="chartData"
                      :xAxisData="chartData.xAxisData"
                    />
                    <Empty v-else />
                  </px-col>
                </px-row>
              </CarouselItem>
            </Carousel>
            <Empty class="qhk-card-empty" v-if="!qhkData && !loading" />
          </div>
        </div>
      </px-col>
    </px-row>
    <LineDialog v-if="dialogVisible" v-model="dialogVisible" :chartData="dialogLineData" />
  </section>
</template>
<style lang="scss" scoped>
@import url("../card.scss");
.screen-card-box {
  height: 387rpx;
}
.qhk-card-empty {
  height: 320rpx;
}
.pointer {
  cursor: pointer;
  :deep(canvas) {
    cursor: pointer;
  }
}
.mg-8 {
  margin: 8rpx 0;
}
.jxk-card-body,
.dk-card-body,
.sk-card-body,
.qhk-card-body {
  height: 320rpx;
  padding: 0 8px;
}
.dk-card-body {
  height: 338rpx;
  background-image: url("/ifp-web-static/image/all/leadScreenNew/dkCardBg.png");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%;
}
.dk-card-body {
  .dk-card-item {
    &:nth-child(n + 3) {
      margin-top: 16rpx;
    }
  }
}
.sk-card-body {
  .row-title {
    text-align: center;
    font-size: 12rpx;
    font-family: AlibabaPuHuiTiM;
    color: #3cb1fb;
    line-height: 16rpx;
    margin-bottom: 5rpx;
  }
  .sk-line-chart {
    height: 124rpx;
  }
}
.chart-box {
  &:nth-child(n + 3) {
    margin-top: 16rpx;
  }
}
</style>
